<template>
  <view class="container">
    <!-- <uni-card :is-shadow="false" is-full>
      <text class="uni-h6"
        >uni-forms
        组件一般由输入框、选择器、单选框、多选框等控件组成，用以收集、校验、提交数据。</text
      >
    </uni-card> -->

    <view class="example">
      <!-- 基础表单校验 -->
      <!-- label-position="top" label-width="auto" 表单标签格式统一换行 -->
      <uni-forms
        ref="valiForm"
        :modelValue="formItemAll.formItems"
        label-position="top"
        label-width="auto"
      >
        <template v-if="deepOption.column">
          <forms-item
            :option="deepOption"
            :forms="formItemAll.formItemC"
            @change="change"
          >
          </forms-item>
        </template>
        <template v-if="deepOption.group">
          <view
            v-for="(groupItem, index) in deepOption.group"
            :key="groupItem.prop"
          >
            <view class="ptb20 size16">{{ groupItem.label }}</view>
            <!-- 小程序端初始化后column与group数据隔离了，不能动态响应，将两部分数据分开处理，最后合并 -->
            <template v-if="groupItem.column">
              <forms-item
                :option="groupItem"
                :forms="formItemAll.formItemG"
                @change="change"
              >
              </forms-item>
            </template>
            <template v-else>
              <view
                style="
                  font-size: 14px;
                  background: #ffffff;
                  color: #a4a4a4;
                  padding: 6px 20px;
                  text-align: center;
                "
                >暂无相关数据</view
              >
            </template>
          </view>
        </template>
        <!-- <template v-else>
            <view
              style="
                font-size: 14px;
                background: #ffffff;
                color: #a4a4a4;
                padding: 6px 20px;
                text-align: center;
              "
              >暂无相关数据</view
            >
          </template> -->
      </uni-forms>
      <button
        v-if="!detail"
        type="primary"
        @click="submit('valiForm')"
        class="ptb16 mt60 mb20"
      >
        提交
      </button>
    </view>
  </view>
</template>

<script>
import formsItem from "./formsItem.vue";
import { deepClone } from "./utils/deepClone.js";
import getTypePropDefault from "./utils/typePropDefault";
import handleAvueOption from "./utils/handleAvueOption";
// import componentObj from "./auniComponents/importIndex.js";
export default {
  name: "a-uni-form",
  components: {
    // ...componentObj,
    formsItem,
  },
  props: {
    form: {
      type: Object,
      default: () => {},
    },
    option: {
      type: Object,
      default: () => {},
    },
    detail: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 小程序不支持props，在小程序中无法通过props给子组件传递值。
      // 不能在子组件方法中直接对duration进行修改，需要使用this.$emit('change')，通知父组件，在父组件中进行修改。
      // 每个组件重新赋值与事件回显通知
      // formItem: this.form,
      formItemAll: {
        formItems: {},
        formItemC: {},
        formItemG: {},
      },
      // 深拷贝配置
      // 可以在父元素处理好再传到Aform组件这里
      deepOption: null,
      dynamicRules: {
        a166126914632983938: {
          rules: [
            {
              required: true,
              errorMessage: "必填项不能为空",
            },
          ],
        },
      },
    };
  },
  computed: {},
  onLoad() {},
  created() {
    // 初始化循环配置生成form绑定默认值
    // if (JSON.stringify(this.form) == "{}") {
    this.creatFormProp();
    // }
    this.useHandleAvueOptionJS();
  },
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.valiForm.setRules(this.dynamicRules);
  },
  watch: {
    formItemAll: {
      deep: true,
      immediate: true,
      handler(newV) {
        // console.log("00000index formItemAll :>> ", newV);
        // 触发value绑定值的交互与更新
        // this.$emit("input", newV);
        // this.$emit("change", newV);
      },
    },
  },
  methods: {
    // a-uni-input组件测试与实现
    // 每一项子项的数据回调
    change(e00000) {
      // console.log("e00000 :>> ", e00000);
      // console.log("this.formItemAll", this.formItemAll);
      this.$nextTick(() => {
        this.formItemAll.formItems = Object.assign(
          this.formItemAll.formItems,
          e00000
        );
      });
      this.$forceUpdate();
    },
    /**
     * @description: 循环配置生成form绑定默认值
     * @return {*}
     */
    creatFormProp() {
      //console.log("1111 :>> ", 1111);
      let deepOption = deepClone(this.option);
      let formItems = {};
      let formItemC = {};
      let formItemG = {};
      // 处理普通表单的column
      if (deepOption.column && deepOption.column.length > 0) {
        deepOption.column.forEach((item) => {
          // this.form[item.prop] = getTypePropDefault(item.type);
          // 深度式响应
          // crud内嵌子表单
          // if (item.type == "customCrud") {
          //   // 子表单部分相关配置在子表单组件内适配
          //   let children = deepClone(item.params.formOption);
          //   this.$set(this.form, item.prop, getTypePropDefault(item.type, children));
          // } else {
          //   this.$set(this.form, item.prop, getTypePropDefault(item.type));
          // }
          // this.$set(this.formItem, item.prop, getTypePropDefault(item.type));
          formItems[item.prop] = getTypePropDefault(item.type);
          formItemC[item.prop] = getTypePropDefault(item.type);
        });
      }
      // 处理分组group
      // 数据扁平化，同column同级，如需处理成对象请使用对象组件
      if (deepOption.group && deepOption.group.length > 0) {
        deepOption.group.forEach((item) => {
          item.column.forEach((item2) => {
            // this.form[item2.prop] = getTypePropDefault(item2.type);
            // 深度式响应
            // this.$set(
            //   this.formItem,
            //   item2.prop,
            //   getTypePropDefault(item2.type)
            // );
            formItems[item.prop] = getTypePropDefault(item.type);
            formItemG[item.prop] = getTypePropDefault(item.type);
          });
        });
      }

      let obj1 = {};
      for (let i in formItemC) {
        obj1[i] = this.form[i] || formItemC[i];
      }
      let obj2 = {};
      for (let i in formItemG) {
        obj1[i] = this.form[i] || formItemG[i];
      }
      this.$set(
        this.formItemAll,
        "formItems",
        Object.assign(formItems, this.form)
      );
      this.$set(this.formItemAll, "formItemC", obj1);
      this.$set(this.formItemAll, "formItemG", obj2);

      this.$forceUpdate();
      console.log("this.formItemAll0000 :>> ", this.formItemAll);
    },

    /**
     * @description: 抽成js调用处理配置数据返回,handleAvueOption.js
     * @return {*}
     */
    useHandleAvueOptionJS() {
      let deepOption = deepClone(this.option);
      // console.log("deepOption :>> ", deepOption);
      // this需传递
      let data = handleAvueOption(deepOption, this.detail, this);
      console.log("data11111111111111111111", data);
      this.deepOption = data;
      this.$forceUpdate();
    },

    /**
     * @description: 点击提交 uni-forms 数据返回
     * @param {*} ref
     * @return {*}
     */
    submit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          // 表单项中有任一request:true;字段就会数据自动绑定
          // 每一项都要配置
          // uni.showToast({
          //   title: `校验通过`,
          // });
          // uni.showModal({
          //   title: `校验通过`,
          //   content: `${JSON.stringify(res)}`,
          //   success: function (res) {
          //     if (res.confirm) {
          //       console.log("用户点击确定");
          //     } else if (res.cancel) {
          //       console.log("用户点击取消");
          //     }
          //   },
          // });
          console.log("uni-forms-onSubmit-res", res);
          console.log("this.formItemAll", this.formItemAll);
          // 合并数据，解决单组件数据绑定问题
          let allFinalData = Object.assign(res, this.formItemAll.formItems);
          console.log("allFinalData", allFinalData);
          // 触发父组件自定义事件
          this.$emit("auniFormMethods", allFinalData);
        })
        .catch((err) => {
          console.log("err", err);
          console.log("this.formItem", this.formItem);
          uni.showToast({
            title: `校验不通过，请检查表单`,
            icon: "error",
            duration: 2000,
          });
        });
    },
  },
};
</script>

<style lang="scss">
.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  margin-left: 10px;
}
</style>
